package com.iqiyi.pps.epg.core.rpc.sginal;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.sginal.*;
import com.iqiyi.pps.epg.api.server.web.sginal.SginalWebService;
import com.iqiyi.pps.epg.core.model.channel.ChannelConfig;
import com.iqiyi.pps.epg.core.model.sginal.*;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.sginal.*;
import com.iqiyi.pps.epg.core.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhang on 2017/4/27.
 */
public class SginalWebServiceImpl implements SginalWebService.Iface {

    private Logger logger = LoggerFactory.getLogger(SginalWebServiceImpl.class);

    public static final int DEL_FAIL = 0;           // 删除失败
    public static final int RESPONSE_SUC = 1;

    public static final int ERROR_NO_ENTITY = -1;
    public static final int ERROR_DELETED_ENTITY = -2;
    public static final int ERROR_WRONG_ENTITY = -1001;
    public static final int ERROR_WRONG_RESOURCE = -1002;
    public static final int ERROR_EXCEPTION = -999;
    public static final int ERROR_API_EXCEPTION = -1003;
    public static final int ERROR_OLD_DATA = -1004;

    public static final int ERROR_REPEAT_NAME = -1105;
    public static final int ERROR_REPEAT_PORT = -1106;
    public static final int ERROR_REPEAT_SERVERIP = -1107;
    public static final int ERROR_REPEAT_SN = -1108;
    public static final int ERROR_OPERTION = -1109;
    public static final int ERROR_HOST = -1110;

    public static final int WARN_DATA_ALREADY = -2001;
    public static final int WARN_RESOURCE_USEING = -2002;
    public static final int WARN_PROGRAM_END = -2003;

    public static final int ERROR_RECORD_USING = -1111;

    private SginalService getSginalService() {
        return WriteSystemLogUtil.getInstance().getSginalService();
    }

    private SginalServerService getSginalServerService() {
        return WriteSystemLogUtil.getInstance().getSginalServerService();
    }

    private ServerClusterService getServerClusterService() {
        return WriteSystemLogUtil.getInstance().getServerClusterService();
    }

    private ServerService getServerService() {
        return WriteSystemLogUtil.getInstance().getServerService();
    }

    private ServerStatusService getServerStatusService() {
        return WriteSystemLogUtil.getInstance().getServerStatusService();
    }

    private SginalStatusService getSginalStatusService() {
        return WriteSystemLogUtil.getInstance().getSginalStatusService();
    }

    private SginalLogService getSginalLogService() {
        return WriteSystemLogUtil.getInstance().getSginalLogService();
    }

    private ChannelService getChannelService() {
        return WriteSystemLogUtil.getInstance().getChannelService();
    }

    private VersionControllerService getVersionControllerService() {return WriteSystemLogUtil.getInstance().getVersionControllerService();}

    @Override
    public int modifySginal(TSginalBase entity, String user) throws TException {
        int result;
        int id;
        List<SginalServer> sginalServerList = new ArrayList<>();
        if ((result = checkSginalBase(entity)) < 0) {
            return result;
        } else {
            sginalServerList = getSginalServer(entity);
            if ((result = checkSginalServer(sginalServerList)) < 0) {
                return result;
            } else {
                result = id = modifySginalBase(entity, user);
                if (result < 0) {
                    return result;
                } else if ((result = clearSginalServer(id)) < 0) {
                    return result;
                } else {
                    return modifySginalServer(sginalServerList, id, user);
                }
            }
        }
    }

    private int checkSginalBase(TSginalBase entity) {
        int result = -1;
        SginalBase sginalBase = null;
        try {
            if (entity != null) {
                List<SginalServer> sginalServers = null;

                if (getSginalService().checkByName(entity.getName(), entity.getId())) {
                    return ERROR_REPEAT_NAME;
                }
                if (getSginalService().checkByPort(entity.getPort(), entity.getId())) {
                    return ERROR_REPEAT_PORT;
                }
                if (entity.getId() > 0) {
                    sginalBase = getSginalService().get(entity.getId());
                    if (sginalBase.getStatus() == SginalBase.STATUS_START) {
                        return ERROR_OPERTION;
                    }
                    if (sginalBase != null && sginalBase.getIsDelete() != SginalBase.IS_DELETE) {
                    } else {
                        return ERROR_NO_ENTITY;
                    }
                }
                JSONObject jsonObject = ApiSginalUtil.status(entity.getAccessServerIp(), null);
                if (jsonObject == null) {
                    return ERROR_HOST;
                }
                return RESPONSE_SUC;
            } else {
                return ERROR_NO_ENTITY;
            }
        } catch (Exception e) {
            logger.error("checkSginalBase", e);
            result = ERROR_EXCEPTION;
            return result;
        }
    }

    private int modifySginalBase(TSginalBase entity, String user) throws TException{
        boolean isCreate = false;
        int id = -1;
        int result = -1;
        SginalBase sginalBase = null;
        try {
            if (entity.getId() > 0) {
                sginalBase = getSginalService().get(entity.getId());
            } else {
                isCreate = true;
                sginalBase = new SginalBase();
            }
            sginalBase.setName(entity.getName());
            sginalBase.setPort(entity.getPort());
            sginalBase.setAccessServerIp(entity.getAccessServerIp());
            sginalBase.setStatus(entity.getStatus());
            sginalBase.setIsDelete(entity.getIsDelete());
            sginalBase.setAuthor(entity.getAuthor());

            getSginalService().update(sginalBase);
            // 记录日志id
            id = sginalBase.getId();

            result = RESPONSE_SUC;
            return id;
        } catch (Exception e) {
            logger.error("modifySginalBase", e);
            result = ERROR_EXCEPTION;
            return result;
        } finally {
            if (isCreate) {
                getSginalLogService().saveLog(id, SginalLogServiceImpl.ACTION_ADD, null, result > 0 ? SginalLogServiceImpl.SUCCESS : SginalLogServiceImpl.FAIL, JSON.toJSONString(sginalBase), user);
            } else {
                getSginalLogService().saveLog(id, SginalLogServiceImpl.ACTION_EDIT, null, result > 0 ? SginalLogServiceImpl.SUCCESS : SginalLogServiceImpl.FAIL, JSON.toJSONString(sginalBase), user);
            }
        }
    }

    private List<SginalServer> getSginalServer(TSginalBase entity) throws TException{
        List<SginalServer> sginalServerList = new ArrayList<>();
        try {
            if (entity != null) {
                // 开始处理信号SginalServer
                List<TSginalServer> tSginalServers = entity.getSginalServers();
                int oldOutputType = 0;
                String oldOutputIp = "";

                for (int i = 0; i < tSginalServers.size(); i++) {
                    TSginalServer tSginalServer = tSginalServers.get(i);
                    SginalServer sginalServer = null;
                    // 空数据 不进行操作
                    if (StringUtils.isBlank(tSginalServer.getOutputIp())) {
                        continue;
                    }
                    sginalServer = new SginalServer();
                    if (tSginalServer.getServerType() != SginalServer.SERVER_TYPE_MIDDLE && tSginalServer.getId() != 0) {
                        sginalServer.setId(tSginalServer.getId());
                    }
                    sginalServer.setIsDelete(SginalServer.IS_NOT_DELETE);
                    sginalServer.setPort(tSginalServer.getPort());
                    if (i == 0) {
                        sginalServer.setInterfaceIp(entity.getAccessServerIp());
                        sginalServer.setInputType(tSginalServer.getInputType());
                        sginalServer.setInputIp(tSginalServer.getInputIp());
                    } else {
                        sginalServer.setInterfaceIp(oldOutputIp);
                        sginalServer.setInputType(oldOutputType);
                        sginalServer.setInputIp(oldOutputIp);
                    }
                    oldOutputType = tSginalServer.getOutputType();
                    oldOutputIp = tSginalServer.getOutputIp();
                    sginalServer.setOutputType(tSginalServer.getOutputType());
                    sginalServer.setOutputIp(tSginalServer.getOutputIp());
                    sginalServer.setSequence(tSginalServer.getSequence());
                    sginalServer.setServerType(tSginalServer.getServerType());
                    sginalServer.setEthNum(tSginalServer.getEthNum());
                    sginalServerList.add(sginalServer);
                }
            }
        } catch (Exception e) {
            logger.error("getSginalServer", e);
        }
        return sginalServerList;
    }

    private int checkSginalServer(List<SginalServer> sginalServerList) {
        try {
            //验证sginalServerList
            for (SginalServer sginalServer : sginalServerList) {
                JSONObject jsonObject = ApiSginalUtil.status(sginalServer.getInterfaceIp(), null);
                if (jsonObject == null) {
                    return ERROR_HOST;
                }
            }
            return RESPONSE_SUC;
        } catch (Exception e) {
            logger.error("checkSginalServer", e);
            return ERROR_EXCEPTION;
        }
    }

    private int clearSginalServer(int id) {
        int result = -1;
        try {
            List<SginalServer> sginalServers = null;

            // 删除所有中继信号传输信息
            sginalServers = getSginalServerService().find(id);
            for (SginalServer sginalServer : sginalServers) {
                if (sginalServer.getServerType().equals(SginalServer.SERVER_TYPE_MIDDLE)) {
                    Map<String, String> params = new HashMap<>();
                    params.put("id", id + "");
                    ApiSginalUtil.delete(sginalServer.getInterfaceIp(), params);
                    sginalServer.setIsDelete(SginalServer.IS_DELETE);
                    getSginalServerService().update(sginalServer);
                }
            }
            result = RESPONSE_SUC;
            return result;
        } catch (Exception e) {
            logger.error("clearSginalServer", e);
            result = ERROR_EXCEPTION;
            return result;
        }
    }

    private int modifySginalServer(List<SginalServer> sginalServerList, int id, String user) throws TException{
        int result = -1;
        try {
            SginalBase sginalBase = getSginalService().get(id);
            //投递数据到信号服务器
            Map<String, String> httpParams = new HashMap<>();
            httpParams.put("channel_name", sginalBase.getName());
            for (SginalServer sginalServer : sginalServerList) {
                httpParams.put("channel_id", sginalBase.getId().toString());
                httpParams.put("input_type", SginalServer.SGINAL_TYPE_NAME[sginalServer.getInputType()]);
                httpParams.put("input_src", SginalServer.SGINAL_TYPE_NAME[sginalServer.getInputType()] + "://" + sginalServer.getInputIp() + ":" + sginalServer.getPort());
                httpParams.put("output_type", SginalServer.SGINAL_TYPE_NAME[sginalServer.getOutputType()]);
                httpParams.put("output_src", SginalServer.SGINAL_TYPE_NAME[sginalServer.getOutputType()] + "://" + sginalServer.getOutputIp() + ":" + sginalServer.getPort());
                if (sginalServer.getServerType().equals(SginalServer.SERVER_TYPE_DEST)) {
                    httpParams.put("udp_networkcard", sginalServer.getEthNum());
                }
                JSONObject httpJsonObject = null;
                if (sginalServer.getId() != null) {
                    httpJsonObject = ApiSginalUtil.edit(sginalServer.getInterfaceIp(), httpParams);
                    if (httpJsonObject != null && ApiSginalUtil.RES_SUCCESS.equals(httpJsonObject.getString("code"))) {
                        sginalServer.setFatherId(sginalBase.getId());
                        getSginalServerService().update(sginalServer);
                    } else {
                        result = ERROR_API_EXCEPTION;
                        return result;
                    }
                } else {
                    httpJsonObject = ApiSginalUtil.add(sginalServer.getInterfaceIp(), httpParams);
                    if (httpJsonObject != null && ApiSginalUtil.RES_SUCCESS.equals(httpJsonObject.getString("code"))) {
                        sginalServer.setFatherId(sginalBase.getId());
                        getSginalServerService().update(sginalServer);
                    } else {
                        sginalBase.setIsDelete(SginalBase.IS_DELETE);
                        getSginalService().update(sginalBase);
                        result = ERROR_API_EXCEPTION;
                        return result;
                    }
                }
            }
            result = RESPONSE_SUC;
            return result;
        } catch (Exception e) {
            logger.error("modifySginalServer", e);
            result = ERROR_EXCEPTION;
            return result;
        } finally {
            getSginalLogService().saveLog(id, SginalLogServiceImpl.ACTION_ADD_SIGNAL, null, result > 0 ? SginalLogServiceImpl.SUCCESS : SginalLogServiceImpl.FAIL, JSON.toJSONString(sginalServerList), user);
        }

    }

    @Override
    public int deleteSginal(int id, String user) throws TException {
        int result = -1;
        try {
            SginalBase sginalBase = getSginalService().get(id);
            if (sginalBase != null && sginalBase.getIsDelete() != SginalBase.IS_DELETE) {
                List<SginalServer> list = getSginalServerService().find(sginalBase.getId());
                for (SginalServer entity : list) {
                    if (entity.getIsDelete() != SginalServer.IS_DELETE) {
                        Map<String, String> params = new HashMap<>();
                        params.put("id", sginalBase.getId().toString());
                        JSONObject jsonObject = ApiSginalUtil.delete(entity.getInterfaceIp(), params);
                        if (jsonObject != null && ApiSginalUtil.RES_SUCCESS.equals(jsonObject.getString("code"))) {
                            entity.setIsDelete(SginalServer.IS_DELETE);
                            getSginalServerService().update(entity);
                        } else {
                            result = ERROR_API_EXCEPTION;
                            return result;
                        }
                    }
                }
                sginalBase.setIsDelete(SginalBase.IS_DELETE);
                getSginalService().update(sginalBase);

                result = RESPONSE_SUC;
                return result;
            } else {
                return ERROR_NO_ENTITY;
            }
        } catch (Exception e) {
            logger.error("deleteSginal", e);
            result = ERROR_EXCEPTION;
            return result;
        } finally {
            getSginalLogService().saveLog(id, SginalLogServiceImpl.ACTION_DEL, null, result > 0 ? SginalLogServiceImpl.SUCCESS : SginalLogServiceImpl.FAIL, "id = " + id, user);
        }
    }

    @Override
    public int forceDeleteSginal(int id, String user) throws TException {
 			int result = -1;
        try {
            SginalBase sginalBase = getSginalService().get(id);
            if (sginalBase != null && sginalBase.getIsDelete() != SginalBase.IS_DELETE) {
                List<SginalServer> list = getSginalServerService().find(sginalBase.getId());
                for (SginalServer entity : list) {
                    if (entity.getIsDelete() != SginalServer.IS_DELETE) {
                            entity.setIsDelete(SginalServer.IS_DELETE);
                            getSginalServerService().update(entity);
                    }
                }
                sginalBase.setIsDelete(SginalBase.IS_DELETE);
                getSginalService().update(sginalBase);
                result= RESPONSE_SUC;
            } else {
                result = ERROR_NO_ENTITY;
            }
            return result;
        } catch (Exception e) {
            logger.error("forceDeleteSginal", e);
			result = ERROR_EXCEPTION;
            return result;
        } finally {
            getSginalLogService().saveLog(id, SginalLogServiceImpl.ACTION_FORCEDEL, null, result > 0 ? SginalLogServiceImpl.SUCCESS : SginalLogServiceImpl.FAIL, "id = " + id, user);
        }
    }

    @Override
    public int startSginal(int id, String user) throws TException {
        int result = -1;
        try {
            SginalBase sginalBase = getSginalService().get(id);
            if (sginalBase != null && sginalBase.getIsDelete() != SginalBase.IS_DELETE) {
                List<SginalServer> list = getSginalServerService().find(sginalBase.getId());
                for (SginalServer entity : list) {
                    if (entity.getIsDelete() != SginalServer.IS_DELETE) {
                        Map<String, String> params = new HashMap<>();
                        params.put("id", sginalBase.getId().toString());
                        params.put("cid", entity.getId().toString());
                        JSONObject jsonObject = ApiSginalUtil.start(entity.getInterfaceIp(), params);
                        if (jsonObject != null && ApiSginalUtil.RES_SUCCESS.equals(jsonObject.getString("code"))) {
                        } else {
                            result = ERROR_API_EXCEPTION;
                            return result;
                        }
                    }
                }
                sginalBase.setStatus(SginalBase.STATUS_START);
                getSginalService().update(sginalBase);
                result = RESPONSE_SUC;
                return result;
            } else {
                result = ERROR_NO_ENTITY;
                return result;
            }
        } catch (Exception e) {
            logger.error("startSginal", e);
            result = ERROR_EXCEPTION;
            return result;
        } finally {
            getSginalLogService().saveLog(id, SginalLogServiceImpl.ACTION_START, null, result > 0 ? SginalLogServiceImpl.SUCCESS : SginalLogServiceImpl.FAIL, "id = " + id, user);
        }
    }

    @Override
    public int stopSginal(int id, String user) throws TException {
        int result = -1;
        try {
            SginalBase sginalBase = getSginalService().get(id);
            if (sginalBase != null && sginalBase.getIsDelete() != SginalBase.IS_DELETE) {
                List<SginalServer> list = getSginalServerService().find(sginalBase.getId());
                for (SginalServer entity : list) {
                    if (entity.getIsDelete() != SginalServer.IS_DELETE) {
                        Map<String, String> params = new HashMap<>();
                        params.put("id", sginalBase.getId().toString());
                        params.put("cid", entity.getId().toString());
                        JSONObject jsonObject = ApiSginalUtil.stop(entity.getInterfaceIp(), params);
                        if (jsonObject != null && ApiSginalUtil.RES_SUCCESS.equals(jsonObject.getString("code"))) {
                        } else {
                            result = ERROR_API_EXCEPTION;
                            return result;
                        }
                    }
                }
                sginalBase.setStatus(SginalBase.STATUS_STOP);
                getSginalService().update(sginalBase);
                result = RESPONSE_SUC;
                return result;
            } else {
                result = ERROR_NO_ENTITY;
                return result;
            }
        } catch (Exception e) {
            logger.error("stopSginal", e);
            result = ERROR_EXCEPTION;
            return result;
        } finally {
            getSginalLogService().saveLog(id, SginalLogServiceImpl.ACTION_STOP, null, result > 0 ? SginalLogServiceImpl.SUCCESS : SginalLogServiceImpl.FAIL, "id = " + id, user);
        }
    }

    @Override
    public TSginalDataPage getSginalData(TPage page, TFilter filter) throws TException {
        return getSginalService().getSginalData(page, filter);
    }

    @Override
    public TSginalLogDataPage getSginalLogData(TPage page, TFilter filter) throws TException {
        return getSginalLogService().getSginalLogData(page, filter);
    }

    @Override
    public int createServer(com.iqiyi.pps.epg.api.model.web.sginal.TServer entity) throws TException {
        if (entity != null) {
            try {
                ServerService serverService = getServerService();
                if (serverService.checkBySn(entity.getSn(), null)) {
                    return ERROR_REPEAT_SN;
                }
                Server server = new Server();
                server.setSn(entity.getSn());
                server.setInsideServerIp(entity.getInsideServerIp());
                server.setOutsideServerIp(entity.getOutsideServerIp());
                server.setPort(entity.getPort());
                server.setProvince(entity.getProvince());
                server.setCity(entity.getCity());
                server.setStatus(entity.getStatus());
                server.setServerType(entity.getServerType());
                server.setIdc(entity.getIdc());
                server.setSystem(entity.getSystem());
                server.setVersion(entity.getVersion());
                server.setHardware(entity.getHardware());
                server.setRemark(entity.getRemark());
                server.setIncluding(entity.getIncluding());
                int id = getServerService().add(server);
                return id;
            } catch (Exception e) {
                logger.error("createServer", e);
                return ERROR_EXCEPTION;
            }
        }
        return ERROR_NO_ENTITY;
    }

    @Override
    public int updateServer(com.iqiyi.pps.epg.api.model.web.sginal.TServer entity) throws TException {
        if (entity != null) {
            ServerService serverService = getServerService();
            if (serverService.checkBySn(entity.getSn(), entity.getId())) {
                return ERROR_REPEAT_SN;
            }
            Server server = getServerService().get(entity.getId());
            if (server != null && server.getStatus() != Server.STATUS_IS_DELETE) {
                try {
                    server.setInsideServerIp(entity.getInsideServerIp());
                    server.setOutsideServerIp(entity.getOutsideServerIp());
                    server.setPort(entity.getPort());
                    server.setProvince(entity.getProvince());
                    server.setCity(entity.getCity());
                    server.setStatus(entity.getStatus());
                    if(entity.getServerType() == server.getServerType() && server.getServerType() == Server.STATUS_INCLUDE){}
                    else {
                        server.setCluster(ServerCluster.UN_ASSIGNED);
                    }
                    server.setServerType(entity.getServerType());
                    server.setIdc(entity.getIdc());
                    server.setSystem(entity.getSystem());
                    server.setVersion(entity.getVersion());
                    server.setHardware(entity.getHardware());
                    server.setRemark(entity.getRemark());


                    server.setIncluding(entity.getIncluding());
                    getServerService().update(server);
                    return RESPONSE_SUC;
                } catch (Exception e) {
                    logger.error("updateServer", e);
                    return ERROR_EXCEPTION;
                }
            }

        }
        return ERROR_NO_ENTITY;
    }

    @Override
    public int checkInsideServerIp(String serverIp) throws TException {
        boolean res =  getServerService().checkInsideServerIp(serverIp);
        if(res) return 1;
        return -1;
    }

    @Override
    public int deleteServer(int id) throws TException {
        Server server = getServerService().get(id);
        if (server != null && server.getStatus() != Server.STATUS_IS_DELETE) {
            try {
                if(server.getCluster() != Server.NOT_ASSIGNED_CLUSTER && getServerService().getServerIncluding(server.getInsideServerIp())!=0 ){
                    return ERROR_RECORD_USING;
                }
                server.setStatus(Server.STATUS_IS_DELETE);
                getServerService().update(server);
                return RESPONSE_SUC;
            } catch (Exception e) {
                logger.error("deleteServer", e);
                return ERROR_EXCEPTION;
            }
        }
        return ERROR_NO_ENTITY;
    }

    @Override
    public TServerDataPage getServersData(TPage page, TFilter filter) throws TException {
        return getServerService().getServersData(page, filter);
    }

    @Override
    public long sginalStatus(int cid, String status) {
        try {
            SginalServer sginalServer = getSginalServerService().get(cid);
            if (sginalServer != null && sginalServer.getIsDelete() != SginalServer.IS_DELETE) {
                SginalStatus sginalStatus = new SginalStatus();
                sginalStatus.setFatherId(sginalServer.getFatherId());
                sginalStatus.setServerIp(sginalServer.getInterfaceIp());
                sginalStatus.setStatusArgs(status);

                Long sginalStatusId = getSginalStatusService().add(sginalStatus);
                long now = System.currentTimeMillis();
                JSONObject statusJson = JSON.parseObject(status);
                int lossSize = Integer.parseInt(statusJson.getJSONObject("udi_info").getString("loss_size"));
                ChannelConfig lossSizeConfig = getChannelService().getConfig(SginalBase.LOSS_SIZE_VALUE_TYPE).get(0);
                long warnTime = sginalServer.getWarnningTime() != null ? sginalServer.getWarnningTime().getTime() : 0L;

                if (lossSize > Long.parseLong(lossSizeConfig.getVal()) && (now - warnTime) > SginalBase.STATUS_TIME) {
                    sginalServer.setWarnningTime(new Timestamp(now));
                    getSginalServerService().update(sginalServer);
                    SginalBase sginalBase = getSginalService().get(sginalServer.getFatherId());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("content", "[警告][信号传输] 频道名称：" + sginalBase.getName() + "(" + sginalBase.getId() + ") 信号服务器：" + sginalServer.getInterfaceIp() + " loss_size:" + lossSize);
                    List<ChannelConfig> usersConfig = getChannelService().getConfig(SginalBase.SGINAL_WARNNING_TYPE);
                    StringBuffer users = new StringBuffer();
                    for (ChannelConfig entity : usersConfig) {
                        users.append(entity.getVal()).append(",");
                    }
                    if (users.length() > 0) {
                        ApiAlertPlatFormUtil.doSend(ApiAlertPlatFormUtil.TOPIC_ID_LIVE_RECORD, ApiAlertPlatFormUtil.SECRET_KEY_EPG, jsonObject.toJSONString(), users.toString(), ApiAlertPlatFormUtil.SEND_TYPE_CHAT);
                    }
                }
                return sginalStatusId;

            } else {
                return ERROR_NO_ENTITY;
            }
        } catch (Exception e) {
            logger.error("sginalStatus", e);
            return ERROR_EXCEPTION;
        }
    }

    @Override
    public TSginalStatusDataPage getSginalStatusData(TPage page, TFilter filter) throws TException {
        return getSginalStatusService().getSginalStatusData(page, filter);
    }

    @Override
    public TServerStatusDataPage getServerStatusData(TPage page, TFilter filter) throws TException {
        return getServerStatusService().getServerStatusData(page, filter);
    }

    @Override
    public TVersionControllerDataPage getVersionControllerData(TPage page, TFilter filter) throws TException {
        return getVersionControllerService().getVersionControllerData(page, filter);
    }

    @Override
    public List<String> getVersionHistory() throws TException {
        return getVersionControllerService().getVersionHistory();
    }



    @Override
    public int delVersionController(int id) throws org.apache.thrift.TException{
        try{
            getVersionControllerService().deleteVersionController(getVersionControllerService().getVersionControllerByServerID(id));
            return RESPONSE_SUC;
        }catch (Exception e){
            logger.error("delVersionController", e);
            return ERROR_EXCEPTION;
        }

    };

    @Override
    public int synVersionController(String serverIp,String hardware,String remark) throws org.apache.thrift.TException{
        VersionController version = null;
        VersionController oldVC =null;
        Server server = getServerService().getZzdByInsideIp(serverIp);
        String mainVersion = getVersionControllerService().getMainVersion();
        if(server==null){
            logger.info("[synVersionController][info]["+serverIp+ " : "+ "not exists"+"]");
            return ERROR_NO_ENTITY;
        }
        int serverId = server.getId();
        try{
            String info = ApiSginalUtil.getVersion(serverIp);
            oldVC = getVersionControllerService().getVersionControllerByServerID(serverId);
            if(info!=null){
                version = getVersionControllerService().string2VersionController(serverId,info,mainVersion);
            }
        }catch (Exception e){
            logger.info("[synVersionController][info]["+serverIp+ " : "+ Constants.getCode(Constants.CODE_ERROR_HTTP_RESULT)+"]");
        }finally {
            try{
                if(version ==null){
                    version = new VersionController(serverId,VersionController.SERVICE_ACCESS_ABNORMAL);
                }

                if(oldVC !=null){
                    version.setId(oldVC.getId());
                }
                version.setRemark(remark);
                version.setHardware(hardware);

                getVersionControllerService().insertOrUpdate(version);

            }catch (Exception e){
                logger.error("[synVersionController][error]", e);
            }finally {
                return RESPONSE_SUC;
            }
        }

    };

    @Override
    public String getMainVersion(){
        return getVersionControllerService().getMainVersion();
    };

    @Override
    public int synVersionStatus(String versions){
        return getVersionControllerService().synVersionStatus(versions);
    };


    @Override
    public int setMainVersion(String versions) {
        return getVersionControllerService().setMainVersion(versions);
    }

    @Override
    public TServerClusterDataPage getServerClusterData(TPage page, TFilter filter) throws TException {
        return getServerClusterService().getServerClusterData(page, filter);
    }

    @Override
    public List<String> getAllCluster() throws TException {
        return null;
    }

    @Override
    public int delServerCluster(int id) throws org.apache.thrift.TException{
        ServerClusterService serverClusterService = getServerClusterService();
        ServerService serverService = getServerService();
        try{
            int taskNum = serverClusterService.includingTaskSum(id);
            if(taskNum>0){
                return ERROR_RECORD_USING;
            }
            List<Server> oldServers = serverClusterService.getAllServerById(id);
            for(Server server:oldServers){
                server.setCluster(ServerCluster.UN_ASSIGNED);
                serverService.update(server);
            }
            serverClusterService.delServerCluster(id);

            return RESPONSE_SUC;
        }catch (Exception e){
            logger.error("delServerCluster", e);
            return ERROR_EXCEPTION;
        }

    }

    @Override
    public int updateServerCluster(TServerCluster entity) throws TException {
        if(entity!=null){
            ServerClusterService serverClusterService = getServerClusterService();
            ServerCluster serverCluster = serverClusterService.get(entity.getId());
            if(serverCluster!=null){
                try{
                    int taskNum = serverClusterService.includingTaskSum(serverCluster.getId());
                    if(taskNum>0 && entity.getStatus() == 0  && serverCluster.getStatus()==1){
                        return ERROR_RECORD_USING;
                    }

                    serverCluster.setStatus(entity.getStatus());
                    serverCluster.setName(entity.getName());
                    serverCluster.setIdc(entity.getIdc());
                    serverClusterService.update(serverCluster);

                    return RESPONSE_SUC;
                }catch (Exception e) {
                    logger.error("updateServerCluster", e);
                    return ERROR_EXCEPTION;
                }
            }
        }
        return ERROR_NO_ENTITY;
    }

    @Override
    public int createServerCluster(TServerCluster entity) throws TException {
        if(entity!=null){
            ServerClusterService serverClusterService = getServerClusterService();
            ServerCluster serverCluster = new ServerCluster();
            try{
                serverCluster.setUser(entity.getUser());
                serverCluster.setStatus(entity.getStatus());
                serverCluster.setName(entity.getName());
                serverCluster.setIdc(entity.getIdc());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                serverCluster.setAddTime(new Timestamp(DateTimeUtil.parseLongFormat(sdf.format(System.currentTimeMillis()))));
                int entityId = serverClusterService.add(serverCluster);

                return entityId;
            }catch (Exception e) {
                logger.error("createServerCluster", e);
                return ERROR_EXCEPTION;
            }
        }
        return ERROR_NO_ENTITY;
    }

    @Override
    public int setClusterServers(List<String> entity, int clusterId) throws TException {
        if(clusterId>0){
            ServerService serverService = getServerService();

            try{
                for (String id: entity){
                    Server server = serverService.get(Integer.parseInt(id));
                    if(server.getCluster()==ServerCluster.UN_ASSIGNED){
                        server.setCluster(clusterId);
                        serverService.update(server);
                    } else {
                        logger.error("Assigned cluster failed","at serverId: "+clusterId);
                        continue;
                    }

                }
                return RESPONSE_SUC;
            }catch (Exception e){
                logger.error("setClusterServers", e);
                return ERROR_EXCEPTION;
            }
        }
        return ERROR_NO_ENTITY;
    }

    @Override
    public int changeClusterServers(List<String> entity, int clusterId) throws TException {
        if(clusterId>0){
            ServerClusterService serverClusterService = getServerClusterService();
            ServerService serverService = getServerService();
            try{
                List<Server> oldServers = serverClusterService.getAllServerById(clusterId);
                for(Server server:oldServers){
                    server.setCluster(ServerCluster.UN_ASSIGNED);
                    serverService.update(server);
                }
                for (String id: entity){
                    Server server = serverService.get(Integer.parseInt(id));
                    if(server.getCluster()==ServerCluster.UN_ASSIGNED){
                        server.setCluster(clusterId);
                        serverService.update(server);
                    }
                    else {
                        logger.error("Assigned cluster failed","at serverId: "+clusterId);
                        continue;
                    }

                }
                return RESPONSE_SUC;
            }catch (Exception e){
                logger.error("changeClusterServers", e);
                return ERROR_EXCEPTION;
            }
        }
        return ERROR_NO_ENTITY;
    }

}
